<template>
  <div class="login">
    <div class="login-header">
      <span>宏烨经纪人</span>
      <span></span>
    </div>
    <div class="login-main">
      <div class="main-1">
        <img src="../assets/1.gif" />
        <h3>
          <span>用心服务</span>
          <span>创造未来</span>
        </h3>
      </div>
      <div class="main-2">
        <van-form>
          <van-field
            v-model="state.ruleForm.username"
            name="手机号"
            label="手机号"
            placeholder="请输入手机号"
            :rules="[{ validator, message: '请填写手机号' }]"
          />
          <van-field
            v-model="state.ruleForm.password"
            name="验证码"
            label="验证码"
            placeholder="请输入验证码"
            :rules="[{ required: true, message: '请填写验证码' }]"
          >
            <template #button>
              <van-button
                style="width:80px"
                size="small"
                type="primary"
                native-type="button"
                :disabled="state.btnDisable"
                @click="sendCheckCode"
              >{{state.btnText}}</van-button>
            </template>
          </van-field>
          <div style="margin: 16px;">
            <van-button
              class="login"
              round
              block
              type="info"
              native-type="submit"
              @click="onSumbit"
            >立即登录</van-button>
          </div>
        </van-form>
      </div>
    </div>
  </div>
</template>
<script>
import axios from "../axios/index.js";
import { Toast } from "vant";
import { defineComponent, reactive } from "vue";
import {useRouter} from "vue-router"
export default defineComponent({
  setup() {
    //初始化路由
    const router=useRouter()
    const state = reactive({
      ruleForm: {
        username: "",
        password: ""
      },
      btnDisable: false,
      btnText: "发送验证码",
      count: 5,
      code: ""
    });
    const validator = val => {
      return /^1[2-9]\d{9}$/.test(val);
    };
    const getCode = () => {
      //验证码随机生成时间
      state.count = Math.floor(Math.random() * 5 + 3);

      //随机生成四位数验证码
      var random = new Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9");
      for (var i = 0; i < 4; i++) {
        let index = Math.floor(Math.random() * 9);
        state.code += random[index];
      }
      //定时器
      setTimeout(() => {
        Toast(`验证码为：${state.code}`);
        console.log(`验证码为：${state.code}`);
      }, state.count * 1000);
      console.log(state.count);
    };
    const sendCheckCode = () => {
      if (/^1[2-9]\d{9}$/.test(state.ruleForm.username)) {
        //调用函数
        Toast("发送成功")
        getCode();

        state.btnDisable = true;
        let timeout = 30; //重置时间
        let timer = null;
        //倒计时
        timer = setInterval(() => {
          timeout--;
          state.btnText = `${timeout}s后重试`;
          if (timeout <= 0) {
            clearInterval(timer);
            state.btnDisable = false;
            state.btnText = "发送验证码";
            state.code = "";
          }
        }, 1000);
      } else {
        Toast("请输入正确手机号");
      }
    };
    const onSumbit = () => {
      if (state.ruleForm.password === state.code) {
        axios
          .get("/login", {
            params:{
              username: state.ruleForm.username
            }
          })
          .then(res => {
            if (res.code === 200) {
              //token值存储本地
              window.localStorage.setItem("token", res.token);
              window.localStorage.setItem('info',JSON.stringify(res.data))
              //路由跳转
              router.push({path:'/index',query:{
                imgs:res.data.imgs,
                name:res.data.name
              }})
              Toast("登录成功");
            } else {
              Toast("手机号未注册");
            }
          });
      } else {
        //判断验证码状态
        if (state.code === "") {
          Toast("验证码失效");
        } else {
          Toast("验证码错误");
        }
      }
    };

    return {
      state,
      validator,
      onSumbit,
      sendCheckCode
    };
  },
  methods: {
    validator(val) {
      return /^1[3-9]\d{9}$/.test(val);
    },
    async onSumbit() {},
    getCode() {
      state.count = Math.floor(Math.random() * 10 + 5);
      setTimeout(() => {
        Toast(`验证码为：`);
        console.log(`验证码为：`);
      }, state.count * 1000);
      console.log(state.count);
    },
    sendCheckCode() {
      state.getCode();

      state.btnDisable = true;
      let timeout = 30; //重置时间
      let timer = null;
      //倒计时
      timer = setInterval(() => {
        timeout--;
        state.btnText = `${timeout}s后重试`;
        if (timeout <= 0) {
          clearInterval(timer);
          state.btnDisable = false;
          state.btnText = "发送验证码";
        }
      }, 1000);
    }
  }
});
</script>
<style lang="scss" scoped>
.login-header {
  display: flex;
  justify-content: space-between;
  height: 50px;
  font-size: 18px;
  background: #1887f6;
  align-items: center;
  color: white;
  span{
    margin-left: 10px;
    margin-right: 10px;
  }
}
.login-main {
  .main-1 {
    text-align: center;
    span {
      margin-left: 20px;
    }
  }
  .main-2 {
    margin-top: 10px;
    .van-field {
      height: 60px;
    }
    .login {
      background: #169bd5;
      color: white;
      font-size: 16px;
      border-radius: 5px;
      border: none;
    }
  }
}
</style>